package com.zzf.juc练习;

public class 生产者与消费者 {

    //面包柜
    static class Guizi{
        private int size;//面包数量
        private int cap;//面包容量

        Guizi(int cap){
            this.cap = cap;
        }

        boolean isFull(){
            return size == cap;
        }
        boolean isEmpty(){
            return size == 0;
        }

        void add(){
            synchronized (this){
                while (this.isFull()){
                    try {
                        System.out.println(Thread.currentThread().getName()+"：面包柜满了，等待中...");
                        this.wait();//此时，当前线程在锁对象下的等待，知道其他线程将其唤醒
                        System.out.println(Thread.currentThread().getName()+"：被唤醒");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                size++;
                System.out.println(Thread.currentThread().getName()+"：放入一个面包，面包数为"+size);
                this.notifyAll();
                Thread.yield();
            }
        }

        void remove() {
            synchronized (this) {
                while (this.isEmpty()) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "：面包柜空了，等待中...");
                        this.wait();//此时，当前线程在锁对象下的等待，知道其他线程将其唤醒
                        System.out.println(Thread.currentThread().getName() + "：被唤醒");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                size--;
                System.out.println(Thread.currentThread().getName() + "：取出一个面包，面包数为" + size);
                this.notifyAll();
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) {
        Guizi guizi = new Guizi(5);
        for (int k = 0; k < 5; k++) {
            new Thread(()->{
                for (int i = 0; i < 100; i++) {
                    guizi.add();
                }
            },"面包师傅"+k).start();

            new Thread(()->{
                for (int i = 0; i < 100; i++) {
                    guizi.remove();
                }
            },"店员"+k).start();
        }
    }
}
